<template>
  <div>
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <button class="btn-create" @click="openUserModal">创建用户</button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search_box">
      <el-card>
        <el-tabs v-model="queryInfo.is_fictitious" class="demo-tabs" @tab-click="searchTable">
          <el-tab-pane :label="item.label" :name="item.value" v-for="item in userTypes" :key="item.value"></el-tab-pane>
        </el-tabs>

        <div class="flex align-center">
          <el-input v-model="queryInfo.phone" style="width: 300px;" class="m-2" size="large" placeholder="搜索用户手机号"
            :prefix-icon="Search" />

          <Select class="margin-left" v-model="queryInfo.status" :data="userStatus" @change="searchTable" />


          <!-- <el-row :gutter="24">
            <el-col :span="20">
              <el-input v-model="queryInfo.phone" style="width: 300px;" class="m-2" size="large" placeholder="搜索用户手机号"
                :prefix-icon="Search" />
            </el-col>

            <el-col :span="4">
              <Select v-model="queryInfo.status" :data="userStatus" @change="searchTable" />
            </el-col>
          </el-row> -->
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="margin-top">
      <el-table ref="multipleTableRef" :data="listData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column property="id" label="用户ID" width="100"></el-table-column>
        <el-table-column property="user_name" label="用户" width="200"></el-table-column>

        <el-table-column label="用户类型">
          <template #default="scope">
            <template v-for="item in userTypes">
              <el-tag class="ml-2" :key="item.id" :color="item.color" v-if="scope.row.is_fictitious === item.value">
                {{ item.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="联系电话" property="phone"></el-table-column>

        <el-table-column label="电子邮箱" property="email"></el-table-column>

        <!-- <el-table-column label="佣金" property="commission_rate"
          v-if="queryInfo.is_fictitious == 1 || queryInfo.is_fictitious == 3">
          <template #default="scope">
            <div>¥{{ scope.row.commission_money || 0 }}</div>
          </template>
        </el-table-column> -->

        <el-table-column label="佣金比例" property="commission_rate"
          v-if="queryInfo.is_fictitious == 1 || queryInfo.is_fictitious == 3">
          <template #default="scope">
            <div>{{
              scope.row.userConfigWithOne?.commission_rate ?
                scope.row.userConfigWithOne.commission_rate * 100
                :
                0 }}%</div>
          </template>
        </el-table-column>

        <!-- <el-table-column label="累计销售额" property="email">
        <template #default="scope">
          <div>¥ {{ scope.row.one_money }}</div>
        </template>
      </el-table-column> -->

        <el-table-column property="status" label="状态">
          <template #default="scope">
            <template v-for="item in userStatus">
              <el-tag class="ml-2" :key="item.id" :type="item.type" v-if="scope.row.status === item.value">
                {{ item.label }}
              </el-tag>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div class="flex align-center">
              <el-button size="small" @click="openUserModal(scope.row)">编辑</el-button>

              <span class="flex margin-left-xs">
                <el-button size="small" type="success" @click="handleUserStatus(scope.row, '1')"
                  v-if="scope.row.status == 0">启用</el-button>

                <el-button size="small" type="info" @click="handleUserStatus(scope.row, '0')" v-else>禁用</el-button>
              </span>

              <el-button class="margin-left-xs" size="small" type="info"
                @click="handleSetUserBrokerage(scope.row)">佣金设置</el-button>

              <el-button class="margin-left-xs" size="small" type="primary"
                @click="viewUserDetails(scope.row)">查看详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="margin-top">
      <Pagination :total="total" @change="changePage" />
    </div>

    <!-- 用户表单 -->
    <UserFormModal ref="userFormModalRef" :userTypeData="userTypes" :userStatusData="userStatus"
      @reload="searchTable" />

    <UserBrokerageFormModal @reload="searchTable" ref="userBrokerageFormModalRef" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, toRef, onMounted, watch } from 'vue'
import Select from '@/components/admin/Select.vue'
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router';
import useTableHook from '@/hooks/useTableHook'
import { GetUserList, UserAddAndEdit } from '@/api/index'
import { RefreshRight } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/admin/Pagination.vue'
import UserFormModal from '@/components/admin/users/UserFormModal.vue';
import UserBrokerageFormModal from '@/components/admin/users/UserBrokerageFormModal.vue'

const router = useRouter();

// 用户表单
const userFormModalRef = ref()

const openUserModal = (data = {}) => {
  userFormModalRef.value.open({
    data: {
      ...data,
      classId: data.is_fictitious
    }
  })
}

// ------------

const userTypes = [
  {
    label: '全部',
    value: ''
  },
  {
    label: '区域代理',
    value: 1,
  },
  // {
  //   label: '店铺',
  //   value: 2,
  // },
  {
    label: '经销商',
    value: 3,
  },
  {
    label: '普通用户',
    value: 0
  },
]

const userStatus = [
  {
    label: '冻结',
    value: 0,
    type: 'error'
  },
  {
    label: '正常',
    value: 1,
    type: 'success'
  }
]

const statusData = [
  {
    label: '全部状态',
    value: ''
  },
  {
    label: '待发货',
    value: 0,
    color: '#f4f4f5'
  },
  {
    label: '发货中',
    value: 1,
    color: '#409eff'
  },
  {
    label: '代签收',
    value: 2,
    color: '#e6a23c'
  },
  {
    label: '已签收',
    value: 3,
    color: '#66c03a'
  },
  {
    label: '结束订单',
    value: 4,
    color: '#909399'
  },
  {
    label: '取消订单',
    value: 5,
    color: '#f56c6c'
  }
]

const queryInfo = ref({
  is_fictitious: '',
  phone: '',
  status: '',
  page: 1,
  limit: 10,
})

const userBrokerageFormModalRef = ref()

// 设置佣金比例
const handleSetUserBrokerage = (record) => {
  userBrokerageFormModalRef.value.open({
    data: {
      uid: record.id
    }
  }, 'edit')
}

const handleUserStatus = (record, status) => {
  let statusText = record.status == 1 ? '禁用' : '启用'

  ElMessageBox.confirm(`确认${statusText}用户: ${record.user_name}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      let newVal = JSON.parse(JSON.stringify(record))

      newVal.status = status

      newVal.method = 'edit'

      const res = await UserAddAndEdit(newVal)

      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })

      searchTable()
    } catch (err) {
      ElMessage({
        type: 'error',
        message: `${statusText}失败!`,
      })
    }
  })
}

// 查看用户详情
const viewUserDetails = (user: any) => {
  // 跳转到用户详情页面
  router.push(`/admin/users/${user.id}`);
};

onMounted(() => {
  initTable()
})

const {
  total,
  listData,
  searchTable,
  initTable,
  changePage,
} = useTableHook(queryInfo.value, GetUserList)
</script>

<style lang="scss">
$primary: #3498db;

/* 头部区域样式 */
/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: white;
  padding: 20px 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.04);
}

.page-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
  position: relative;
}

.page-header h1::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -8px;
  width: 40px;
  height: 3px;
  background-color: $primary;
  border-radius: 3px;
}

.btn-create {
  background-color: $primary;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.btn-create:hover {
  background-color: darken($primary, 10%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 153, 225, 0.3);
}

.btn-create::before {
  content: '+';
  font-size: 18px;
  font-weight: 500;
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.merchant-name {
  color: #e74c3c;
}

.back-link {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  color: #7f8c8d;
  text-decoration: none;
  transition: color 0.3s;
  margin-top: 5px;
}

.back-link:hover {
  color: #e74c3c;
}

.back-link i {
  margin-right: 5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-weight: 600;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #c0392b;
}

.btn-primary i {
  margin-right: 5px;
}
</style>
